<template>
  <div class="ai-chat-float">
    <!-- 漂浮按钮 -->
    <div 
      class="float-button" 
      :class="{ 'active': isOpen }"
      @click="toggleChat"
    >
      <el-icon class="float-icon">
        <Message v-if="!isOpen" />
        <Close v-else />
      </el-icon>
      <div v-if="hasUnread && !isOpen" class="unread-dot"></div>
    </div>

    <!-- 聊天窗口 -->
    <transition name="chat-slide">
      <div v-if="isOpen" class="chat-window">
        <!-- 聊天窗口头部 - 改成蓝色主题 -->
        <div class="chat-header blue-theme">
          <div class="header-info">
            <el-avatar :size="32" class="ai-avatar">
              <el-icon><Avatar /></el-icon>
            </el-avatar>
            <div class="header-text">
              <h4>MES AI助手</h4>
              <span class="status">在线服务中</span>
            </div>
          </div>
          <div class="header-actions">
            <el-button 
              text 
              :icon="Delete" 
              @click="clearChatHistory"
              class="action-btn clear-btn"
              title="清理聊天记录"
            />
            <el-button 
              text 
              :icon="Minus" 
              @click="minimizeChat"
              class="action-btn"
              title="最小化"
            />
            <el-button 
              text 
              :icon="Close" 
              @click="closeChat"
              class="action-btn"
              title="关闭"
            />
          </div>
        </div>

        <!-- 聊天消息区域 -->
        <div class="chat-messages" ref="messagesContainer">
          <!-- 增强版欢迎消息 -->
          <div v-if="messages.length === 0" class="welcome-message">
            <div class="welcome-content">
              <div class="ai-avatar-large">
                <el-icon><Avatar /></el-icon>
              </div>
              <h4>👋 您好！我是MES AI助手</h4>
              <p class="welcome-desc">
                我是您的智能助手，可以帮助您解决MES系统相关的问题。
                <br>无论是操作指导、功能介绍还是故障排查，我都很乐意为您服务！
              </p>
              <div class="quick-actions">
                <el-button 
                  v-for="action in quickActions" 
                  :key="action.text"
                  size="small" 
                  type="primary"
                  plain
                  @click="sendQuickMessage(action.text)"
                  class="quick-btn"
                >
                  <el-icon class="btn-icon">
                    <component :is="action.icon" />
                  </el-icon>
                  {{ action.text }}
                </el-button>
              </div>
              <div class="tips">
                <el-text size="small" type="info">
                  💡 提示：您可以直接输入问题，或点击上方快速选项
                </el-text>
              </div>
            </div>
          </div>

          <!-- 消息列表 -->
          <div 
            v-for="(message, index) in messages" 
            :key="index" 
            class="message-item"
            :class="{ 'user-message': message.role === 'user', 'ai-message': message.role === 'assistant' }"
          >
            <div v-if="message.role === 'assistant'" class="message-avatar">
              <el-avatar :size="28">
                <el-icon><Avatar /></el-icon>
              </el-avatar>
            </div>
            <div class="message-content">
              <div class="message-bubble">
                <div class="message-text" v-html="formatMessageContent(message.content)"></div>
                <div class="message-time">{{ formatTime(message.timestamp) }}</div>
              </div>
            </div>
            <div v-if="message.role === 'user'" class="message-avatar">
              <el-avatar :size="28">
                <el-icon><User /></el-icon>
              </el-avatar>
            </div>
          </div>

          <!-- 正在输入指示器 -->
          <div v-if="isTyping" class="typing-indicator">
            <div class="message-avatar">
              <el-avatar :size="28">
                <el-icon><Avatar /></el-icon>
              </el-avatar>
            </div>
            <div class="typing-content">
              <div class="typing-bubble">
                <div class="typing-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 智能推荐区域 -->
        <div v-if="suggestedReplies.length > 0" class="suggestions-area">
          <div class="suggestions-header" @click="toggleSuggestions">
            <div class="suggestions-header-left">
              <el-icon class="suggestions-icon">
                <Star />
              </el-icon>
              <span class="suggestions-title">智能推荐</span>
            </div>
            <el-button 
              text 
              size="small" 
              class="toggle-btn"
              :title="isSuggestionsExpanded ? '收起' : '展开'"
            >
              <el-icon class="toggle-icon">
                <ArrowUp v-if="isSuggestionsExpanded" />
                <ArrowDown v-else />
              </el-icon>
            </el-button>
          </div>
          <transition name="suggestions-collapse">
            <div v-show="isSuggestionsExpanded" class="suggestions-list">
              <div 
                v-for="(suggestion, index) in suggestedReplies" 
                :key="index"
                class="suggestion-item"
                @click="selectSuggestion(suggestion)"
              >
                <span class="suggestion-text">{{ suggestion }}</span>
                <el-icon class="suggestion-arrow">
                  <Right />
                </el-icon>
              </div>
            </div>
          </transition>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input">
          <div class="input-container">
            <el-input
              v-model="inputMessage"
              placeholder="输入您的问题..."
              type="textarea"
              :rows="1"
              resize="none"
              @keydown.enter.prevent="handleEnterKey"
              @input="handleInput"
              class="message-input"
            />
            <el-button 
              type="primary" 
              :icon="Promotion"
              @click="sendMessage"
              :disabled="!inputMessage.trim() || isLoading"
              :loading="isLoading"
              class="send-btn"
            />
          </div>
        </div>
      </div>
    </transition>

    <!-- 确认清理对话框 -->
    <el-dialog
      v-model="showClearDialog"
      title="确认清理"
      width="300px"
      center
    >
      <div class="clear-dialog-content">
        <el-icon class="warning-icon"><WarningFilled /></el-icon>
        <p>确定要清理所有聊天记录吗？</p>
        <p class="warning-text">此操作不可恢复</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showClearDialog = false">取消</el-button>
          <el-button type="danger" @click="confirmClearHistory">
            确定清理
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted, onUnmounted, watch } from 'vue'
import { 
  Message, 
  Close, 
  Avatar, 
  User, 
  Minus, 
  Promotion,
  Delete,
  WarningFilled,
  QuestionFilled,
  Tools,
  DocumentCopy,
  Service,
  Star,
  Right,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAiChatStore } from '@/stores/aiChat'

// 使用AI聊天store
const chatStore = useAiChatStore()

// 响应式数据
const isOpen = ref(false)
const hasUnread = ref(false)
const inputMessage = ref('')
const messagesContainer = ref<HTMLElement>()
const showClearDialog = ref(false)
const isSuggestionsExpanded = ref(true) // 智能推荐区域展开状态

// 从store获取数据
const messages = computed(() => chatStore.messages)
const isLoading = computed(() => chatStore.isLoading)
const suggestedReplies = computed(() => chatStore.suggestedReplies)

// 模拟正在输入状态
const isTyping = ref(false)

// 增强版快速操作按钮
const quickActions = [
  { text: '系统功能介绍', icon: Tools },
  { text: '操作指导', icon: DocumentCopy },
  { text: '常见问题', icon: QuestionFilled },
  { text: '联系客服', icon: Service }
]

// 切换聊天窗口
const toggleChat = async () => {
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    hasUnread.value = false
    // 滚动到底部
    await nextTick()
    scrollToBottom()
  }
}

// 关闭聊天窗口
const closeChat = () => {
  isOpen.value = false
}

// 最小化聊天窗口
const minimizeChat = () => {
  isOpen.value = false
}

// 清理聊天记录
const clearChatHistory = () => {
  showClearDialog.value = true
}

// 确认清理聊天记录
const confirmClearHistory = () => {
  chatStore.clearMessages()
  showClearDialog.value = false
  ElMessage.success('聊天记录已清理')
}

// 发送快速消息
const sendQuickMessage = (text: string) => {
  inputMessage.value = text
  sendMessage()
}

// 选择智能推荐
const selectSuggestion = (suggestion: string) => {
  inputMessage.value = suggestion
  sendMessage()
}

// 切换智能推荐区域展开状态
const toggleSuggestions = () => {
  isSuggestionsExpanded.value = !isSuggestionsExpanded.value
}

// 处理输入
const handleInput = () => {
  // 可以添加输入状态处理
}

// 处理回车键
const handleEnterKey = (event: KeyboardEvent) => {
  if (!event.shiftKey) {
    sendMessage()
  }
}

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim()
  if (!message || isLoading.value) return

  inputMessage.value = ''
  isTyping.value = true

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  try {
    // 使用store发送消息
    const response = await chatStore.sendMessage(message)
    
    isTyping.value = false
    
    // 如果窗口关闭，显示未读标识
    if (!isOpen.value) {
      hasUnread.value = true
    }

    // 获取智能推荐（异步执行，不阻塞UI）
    if (response) {
      chatStore.getSuggestedReplies(response.reply)
    }

  } catch (error: any) {
    console.error('发送消息失败:', error)
    isTyping.value = false
    ElMessage.error('发送消息失败，请重试')
  }

  // 滚动到底部
  await nextTick()
  scrollToBottom()
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 格式化消息内容
const formatMessageContent = (content: string) => {
  // 处理换行
  let formatted = content.replace(/\n/g, '<br>')
  
  // 处理代码块
  formatted = formatted.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
  
  // 处理行内代码
  formatted = formatted.replace(/`([^`]+)`/g, '<code>$1</code>')
  
  // 处理加粗
  formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  
  return formatted
}

// 格式化时间
const formatTime = (timestamp: string) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) { // 小于1分钟
    return '刚刚'
  } else if (diff < 3600000) { // 小于1小时
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 小于24小时
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else {
    return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
  }
}

// 监听消息变化，自动滚动
watch(messages, async () => {
  await nextTick()
  scrollToBottom()
}, { deep: true })

// 组件挂载时的处理
onMounted(() => {
  // 可以添加一些初始化逻辑
})

// 点击外部关闭
const handleClickOutside = (event: Event) => {
  const target = event.target as Element
  if (isOpen.value && !target.closest('.ai-chat-float')) {
    // 可以选择是否点击外部关闭
    // closeChat()
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.ai-chat-float {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 9999;
}

/* 漂浮按钮 */
.float-button {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 20px rgba(30, 58, 138, 0.4);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.float-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 30px rgba(30, 58, 138, 0.6);
}

.float-button.active {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.float-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: radial-gradient(circle at center, rgba(255,255,255,0.3) 0%, transparent 70%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.float-button:hover::before {
  opacity: 1;
}

.float-icon {
  font-size: 24px;
  color: white;
  transition: transform 0.3s ease;
}

.float-button:hover .float-icon {
  transform: scale(1.1);
}

/* 未读消息点 */
.unread-dot {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 12px;
  height: 12px;
  background: #ff4757;
  border-radius: 50%;
  border: 2px solid white;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(255, 71, 87, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(255, 71, 87, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(255, 71, 87, 0);
  }
}

/* 聊天窗口 */
.chat-window {
  position: absolute;
  bottom: 80px;
  right: 0;
  width: 360px;
  height: 500px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border: 1px solid #e1e8ed;
}

/* 聊天窗口动画 */
.chat-slide-enter-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.chat-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.chat-slide-enter-from {
  opacity: 0;
  transform: translateY(20px) scale(0.95);
}

.chat-slide-leave-to {
  opacity: 0;
  transform: translateY(20px) scale(0.95);
}

/* 聊天头部 */
.chat-header {
  padding: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 蓝色主题头部 */
.chat-header.blue-theme {
  background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
  box-shadow: 0 2px 10px rgba(30, 58, 138, 0.3);
}

.header-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.ai-avatar {
  background: rgba(255, 255, 255, 0.2);
  color: white;
}

.header-text h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.status {
  font-size: 12px;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  gap: 4px;
}

.action-btn {
  color: white !important;
  padding: 4px !important;
  min-height: auto !important;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.1) !important;
}

.clear-btn:hover {
  background: rgba(239, 68, 68, 0.2) !important;
}

/* 消息区域 */
.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #f8fafc;
}

.chat-messages::-webkit-scrollbar {
  width: 4px;
}

.chat-messages::-webkit-scrollbar-track {
  background: transparent;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #cbd5e0;
  border-radius: 2px;
}

/* 欢迎消息 */
.welcome-message {
  text-align: center;
  padding: 20px 0;
}

.ai-avatar-large {
  width: 60px;
  height: 60px;
  margin: 0 auto 16px;
  background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.welcome-content h4 {
  margin: 0 0 8px 0;
  color: #2d3748;
  font-size: 18px;
}

.welcome-content p {
  margin: 0 0 20px 0;
  color: #718096;
  font-size: 14px;
}

.welcome-desc {
  line-height: 1.6;
  margin-bottom: 24px !important;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

.quick-btn {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 8px;
  text-align: left;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.quick-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
}

.btn-icon {
  font-size: 16px;
}

.tips {
  padding: 12px;
  background: rgba(59, 130, 246, 0.1);
  border-radius: 8px;
  border-left: 3px solid #3b82f6;
}

/* 消息项 */
.message-item {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}

.message-item.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  flex: 1;
  max-width: 80%;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 16px;
  position: relative;
}

.ai-message .message-bubble {
  background: white;
  border: 1px solid #e2e8f0;
  margin-right: 40px;
}

.user-message .message-bubble {
  background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
  color: white;
  margin-left: 40px;
}

.message-text {
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 4px;
}

.message-time {
  font-size: 11px;
  opacity: 0.7;
}

/* 正在输入指示器 */
.typing-indicator {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.typing-content {
  flex: 1;
}

.typing-bubble {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 16px;
  padding: 12px 16px;
  margin-right: 40px;
}

.typing-dots {
  display: flex;
  gap: 4px;
}

.typing-dots span {
  width: 6px;
  height: 6px;
  background: #cbd5e0;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 智能推荐区域 */
.suggestions-area {
  padding: 12px 16px 0;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
}

.suggestions-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  cursor: pointer;
  padding: 4px 0;
  transition: all 0.2s ease;
}

.suggestions-header:hover {
  background: rgba(30, 58, 138, 0.05);
  border-radius: 6px;
  padding: 4px 8px;
}

.suggestions-header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.suggestions-icon {
  color: #1e3a8a;
  font-size: 16px;
  animation: pulse-icon 2s infinite;
}

.suggestions-title {
  color: #1e3a8a;
  font-size: 13px;
  font-weight: 600;
}

.toggle-btn {
  color: #1e3a8a !important;
  padding: 2px !important;
  min-height: auto !important;
  transition: all 0.2s ease;
}

.toggle-btn:hover {
  background: rgba(30, 58, 138, 0.1) !important;
  transform: scale(1.1);
}

.toggle-icon {
  font-size: 14px;
  transition: transform 0.3s ease;
}

.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 12px;
}

.suggestion-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  padding: 10px 14px;
  background: white;
  border: 1px solid rgba(30, 58, 138, 0.15);
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-size: 13px;
  color: #1e3a8a;
  font-weight: 500;
  position: relative;
  overflow: hidden;
}

.suggestion-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(30, 58, 138, 0.08), transparent);
  transition: left 0.5s;
}

.suggestion-item:hover::before {
  left: 100%;
}

.suggestion-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(30, 58, 138, 0.15);
  background: linear-gradient(135deg, #1e3a8a, #3b82f6);
  color: white;
  border-color: #1e3a8a;
}

.suggestion-text {
  flex: 1;
  text-align: left;
  line-height: 1.4;
}

.suggestion-arrow {
  font-size: 14px;
  opacity: 0.6;
  transition: all 0.3s ease;
}

.suggestion-item:hover .suggestion-arrow {
  opacity: 1;
  transform: translateX(2px);
}

@keyframes pulse-icon {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
}

/* 输入区域 */
.chat-input {
  padding: 16px;
  background: white;
  border-top: 1px solid #e2e8f0;
}

.input-container {
  display: flex;
  gap: 8px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
}

.message-input :deep(.el-textarea__inner) {
  border-radius: 20px;
  border: 1px solid #e2e8f0;
  padding: 12px 16px;
  font-size: 14px;
  resize: none;
  max-height: 80px;
}

.message-input :deep(.el-textarea__inner):focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.send-btn {
  border-radius: 50%;
  width: 40px;
  height: 40px;
  padding: 0;
  background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
  border: none;
}

.send-btn:hover {
  background: linear-gradient(135deg, #1e40af 0%, #2563eb 100%);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-window {
    width: 320px;
    height: 450px;
  }
  
  .ai-chat-float {
    bottom: 15px;
    right: 15px;
  }
  
  .float-button {
    width: 50px;
    height: 50px;
  }
  
  .float-icon {
    font-size: 20px;
  }
}

/* 清理对话框样式 */
.clear-dialog-content {
  text-align: center;
  padding: 20px 0;
}

.warning-icon {
  font-size: 48px;
  color: #f59e0b;
  margin-bottom: 16px;
}

.clear-dialog-content p {
  margin: 8px 0;
  color: #374151;
}

.warning-text {
  color: #ef4444 !important;
  font-size: 12px;
  font-weight: 500;
}
</style> 